#!/usr/bin/python
from PyQt5.QtCore import QAbstractTableModel,QModelIndex
from PyQt5.QtCore import QDateTime, QTime,Qt,QTimer,pyqtSignal,QSettings,QDir
from PyQt5.QtSql import QSqlQueryModel,QSqlQuery
from PyQt5.QtWidgets import QAction, QPushButton, QDesktopWidget,QAbstractItemView, QMainWindow, QApplication, QMessageBox, QCheckBox, QHBoxLayout,QFileDialog,QLabel, QFileDialog,QStyle,QMenu,QLineEdit
from PyQt5 import QtGui,QtCore
from PyQt5 import  QtWidgets,QtSql
import os
import re
import getpath
import config_json
import subprocess
import sys
import ui_mainw
from ShellWidget import ShellWidget
def mylistdir(p,f):
    a=os.listdir(p)
    fs=myfind(a,f)
    return(fs)
def myfind(l,p):
    lr=[];
    #logging.info p
    p1=p.replace(".",r"\.")
    p2=p1.replace("*",".*")
    p2=p2+"$"
    for a in l:
        #logging.info a
        if  re.search(p2,a,re.IGNORECASE)==None :
           pass
           #logging.info "pass"
        else:
           lr.append(a)
       #logging.info "append"
    return lr
if sys.platform == "linux":
    cs0=r"/mnt/chemi/仪器采集/ELTRACSI"
    cs1=r"/mnt/chemi/仪器采集/ELTRACSI_back"
    cs2=r"/mnt/chemi/仪器采集/采集后未删除文件"
    on0=r"/mnt/chemi/仪器采集/caiji/leco_on"
    on1=r"/mnt/chemi/仪器采集/caiji/leco_on_back"
    on2=r"/mnt/chemi/仪器采集/采集后未删除文件"
else:
    cs0 = r"\\10.0.114.230\化学分析室\仪器采集\ELTRACSI"
    cs1 = r"\\10.0.114.230\化学分析室\仪器采集\ELTRACSI_back"
    cs2 = r"\\10.0.114.230\化学分析室\仪器采集\采集后未删除文件"
    on0 = r"\\10.0.114.230\化学分析室\仪器采集\caiji\leco_on"
    on1 = r"\\10.0.114.230\化学分析室\仪器采集\caiji\leco_on_back"
    on2 = r"\\10.0.114.230\化学分析室\仪器采集\采集后未删除文件"
def removeOne(fname,p0,p1,p2):        
    logging.info(fname)
    f=os.path.splitext(fname)
    uploads=mylistdir(p1,f[0]+"*")
    if len(uploads)>0:
        if sys.platform == "linux":
            cmd="mv %s %s" %(os.path.join(p0,fname),p2)
        else:
            cmd="move %s %s" %(os.path.join(p0,fname),p2)
        logging.info(cmd)
        os.system(cmd)
def cs():
    fs=mylistdir(cs0,"*.*")
    for f in fs:
        removeOne(f,cs0,cs1,cs2)
def onh():
    fs=mylistdir(on0,"*.*")
    for f in fs:
        removeOne(f,on0,on1,on2)        
def removeOld():
    cs()
    onh()
class TrayIcon(QtWidgets.QSystemTrayIcon):
    def __init__(self,MainWindow,parent=None):
        super(TrayIcon, self).__init__(parent)
        self.ui = MainWindow
        MainWindow.updated.connect(self.showMsg)
        self.createMenu()
        self.ui.show()#Maximized()
    def remove(self):
        removeOld()
    def createMenu(self):
        self.menu = QtWidgets.QMenu()
        self.showAction1 = QtWidgets.QAction("show", self, triggered=self.show_window)
        self.showAction2 = QtWidgets.QAction("remove captured", self,triggered=self.remove)
        self.showAction3 = QtWidgets.QAction("hide", self, triggered=self.hide_window)
        self.quitAction = QtWidgets.QAction("退出", self, triggered=self.quit)
 
        self.menu.addAction(self.showAction1)
        self.menu.addAction(self.showAction2)
        self.menu.addAction(self.showAction3)
        self.menu.addAction(self.quitAction)
        self.setContextMenu(self.menu)
 
        #设置图标
        self.setIcon(QtGui.QIcon(os.path.join(getpath.getpath(),"work.ico")))
        self.icon = self.MessageIcon()
 
        #把鼠标点击图标的信号和槽连接
        self.activated.connect(self.onIconClicked)
 
    def showMsg(self,msg):
        self.showMessage("Message", msg, self.icon)
 
    def show_window(self):
        #若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.ui.showNormal()
        self.ui.activateWindow()

    def hide_window(self):
        #若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.ui.showMinimized()
 
    def quit(self):
        QtWidgets.qApp.quit()
 
    #鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击
    def onIconClicked(self, reason):
        if reason == 2 or reason == 3:
            # self.showMessage("Message", "skr at here", self.icon)
            if self.ui.isMinimized() or not self.ui.isVisible():
                #若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
                self.ui.showNormal()
                self.ui.activateWindow()
                self.ui.setWindowFlags(QtCore.Qt.Window)
                self.ui.show()
            else:
                #若不是最小化，则最小化
                self.ui.showMinimized()
                self.ui.setWindowFlags(QtCore.Qt.SplashScreen)
                self.ui.show()
                # self.ui.show()
class MainW(QMainWindow):
    updated = pyqtSignal(str)
    # def contextMenuEvent(self, event):
    #     menu = QMenu(self)
    #     i=0
    #     for one in config_json.setting["apps"]:
    #         oneAction = menu.addAction(one)
    #         oneAction.triggered.connect( lambda boo,val=i: self.openApp(val))
    #         i+=1
    #     action = menu.exec_(self.mapToGlobal(event.pos()))
    def openApp(self,i):
        # logging.info(action,dir(action))
        logging.info(i)
        cmds=[config_json.setting["apps"][i],]
        self.exec_cmds(cmds)
    def closeEvent(self, event):
        config_json.write_setting()
        event.accept()
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = ui_mainw.Ui_MainWindow()
        self.ui.setupUi(self)
        self.shell=ShellWidget(self)
        # self.ui.verticalLayout.addWidget(self.shell)
        self.setWindowIcon(QtGui.QIcon(os.path.join(getpath.getpath(),"work.ico")))
        # self.setWindowState(Qt.WindowMaximized)
        config_json.read_setting()
        self.show_hidden=config_json.setting["hidden"]==1
        # self.setWindowFlags(Qt.WindowStaysOnTopHint)
        # self.timer = QTimer(self)
        # self.timer.timeout.connect(self.run)
        # self.timer.start(10*60*1000)
        self.label=QLabel(self)
        self.txt=""
        self.statusBar().addWidget(self.label)
        # self.button=QPushButton(self)
        # self.button.setText("run")
        # self.button.clicked.connect(self.run)
        # self.statusBar().addWidget(self.button)
        # self.statusBar().addWidget(self.button2)
        self.button_cs=QPushButton(self)
        self.button_cs.setText("cs")
        self.button_cs.clicked.connect(self.button_cs_pressed)
        self.statusBar().addWidget(self.button_cs)
        self.button_on=QPushButton(self)
        self.button_on.setText("on")
        self.button_on.clicked.connect(self.button_on_pressed)
        self.statusBar().addWidget(self.button_on)
        self.action_clip = QtWidgets.QAction(self)
        self.action_clip.setObjectName("action_clip")
        self.action_clip.setText("clip->env")
        self.action_clip.setShortcut("Ctrl+V")
        self.action_clip.triggered.connect(self.clip)
    
        # self.action_remove = QtWidgets.QAction(self)
        # self.action_remove.setText("remove")
        # self.action_remove.triggered.connect(removeOld)
    
        self.model = QtWidgets.QFileSystemModel()
        # self.model.setFilter(QDir.Hidden QDir.Dirs | QDir.Drives | QDir.NoDotAndDotDot | QDir.AllDirs)#QDir.Hidden & QDir. AllDirs)
# 'AccessMask', 'AllDirs', 'AllEntries', 'CaseSensitive', 'Dirs', 'DirsFirst', 'DirsLast', 'Drives', 'Executable', 'Files', 'Filter', 'Filters', 'Hidden', 'IgnoreCase', 'LocaleAware', 'Modified', 'Name', 'NoDot', 'NoDotAndDotDot', 'NoDotDot', 'NoFilter', 'NoSort', 'NoSymLinks', 'PermissionMask', 'Readable', 'Reversed', 'Size', 'SortByMask', 'SortFlag', 'SortFlags', 'System', 'Time', 'Type', 'TypeMask', 'Unsorted', 'Writable'        
        # self.model.setFilter(QDir.Hidden | QDir.AllEntries)#QDir.Hidden & QDir. AllDirs)
# filter << "*.jpg" << "*.png" << "*.bmp" << "*.gif";
# model->setNameFilters(filter);        
            
        self.ui_treeView=self.ui.treeView
        self.ui_treeView.setSortingEnabled(True)
        self.ui_treeView.setModel(self.model)
        self.ui_treeView.doubleClicked.connect(self.tv_double)
        
        # self.centralwidget = QtWidgets.QWidget(self)
        # self.v=QtWidgets.QVBoxLayout(self.centralwidget)
        self.l=self.ui.lineEdit
        self.l.editingFinished.connect(self.edit_finish)
        # self.v.addWidget(self.l)        
        # self.v.addWidget(self.ui_treeView)
        # self.setCentralWidget(self.centralwidget)
        self.ui_treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui_treeView.customContextMenuRequested.connect(self.openMenu)
        bar=self.menuBar()
        #向菜单栏中添加新的QMenu对象，父菜单
        # file=bar.addMenu('Action')
        # if sys.platform == "linux":
        #     pass
        # else:
        #     file.addAction(self.action_clip)
        # file.addAction(self.action_remove)
        self.action_apps=self.ui.action_apps
        self.action_apps.setText("apps")
        self.action_apps.triggered.connect(self.show_dlgapp)
        self.ui.action_version.triggered.connect(self.version)
        self.ui.action_exit.triggered.connect(self.close)
        self.ui.actionQt.triggered.connect(QtWidgets.qApp.aboutQt)
        # file.addAction(self.action_apps)
        # i=0
        # for one in config_json.setting["apps"]:
        #     oneAction = QtWidgets.QAction(self)
        #     oneAction.setText(one)
        #     oneAction.triggered.connect( lambda boo,val=i: self.openApp(val))
        #     file.addAction(oneAction)
        #     i+=1

        tb=self.addToolBar('File')
        if sys.platform == "linux":
            pass
        else:
            tb.addAction(self.action_clip)
        tb.addAction(self.action_apps)
        # tb.addAction(quit)
        # self.run()
        self.linux=QtWidgets.QWidget()
        self.p_shutdown=QtWidgets.QPushButton("shutdown")
        self.p_shutdown.clicked.connect(self.shutdown)
        v=QtWidgets.QVBoxLayout(self.linux)
        v.addWidget(self.p_shutdown)
        self._linux_dock = QtWidgets.QDockWidget()
        self._linux_dock.setWindowTitle('linux')
        self._linux_dock.setWidget(self.linux)
        self.addDockWidget(Qt.RightDockWidgetArea, self._linux_dock)
        self._linux_dock.setVisible(False)
        # from cv1 import Cv1
        # self.cv=Cv1()
        # self._cv_dock = QtWidgets.QDockWidget()
        # self._cv_dock.setWindowTitle('cv')
        # self._cv_dock.setWidget(self.cv)
        # self.addDockWidget(Qt.RightDockWidgetArea, self._cv_dock)

        # self._linux_dock.setVisible(False)

        self._dev_dock = QtWidgets.QDockWidget()
        self._dev_dock.setWindowTitle('shell')
        # self._bookmark_widget.open_bookmark.connect(self.load_url)
        # self._bookmark_widget.open_bookmark_in_new_tab.connect(self.load_url_in_new_tab)
        self._dev_dock.setWidget(self.shell)
        self.addDockWidget(Qt.RightDockWidgetArea, self._dev_dock)
        self._dev_dock.setVisible(False)
        
        self._fav=QtWidgets.QListWidget(self)
        self.reset_fav()
        self._fav.itemClicked.connect(self.fav_click)
        self._fav_dock = QtWidgets.QDockWidget()
        self._fav_dock.setWindowTitle('favorite')
        self._fav_dock.setWidget(self._fav)
        self._fav_dock.setVisible(False)
        
        self.addDockWidget(Qt.RightDockWidgetArea, self._fav_dock)
        self.ui.action_delete.triggered.connect(self.delete)
        self.ui.action_copy.triggered.connect(self.copy)
        self.ui.action_paste.triggered.connect(self.paste)
        self.ui.pushButton_favorite.clicked.connect(self.favorite)
        self.ui.action_favorite.triggered.connect(self.show_favorite)
        self.ui.pushButton_new_folder.clicked.connect(self.new_folder)
        self.ui.checkBox_hidden.clicked.connect(self.file_hidden)
        self.drop_hidden=False
        self.ui.pushButton_drop.clicked.connect(self.drop_click)
        self.drop_click()
        self.file_hidden()
        self.goto(".")
        self.timer=None
        self.timer_run=False
        self.timer_chk=QtWidgets.QCheckBox(self)
        self.timer_chk.setText("uploads")
        self.timer_chk.setChecked(self.timer_run)
        self.timer_chk.clicked.connect(self.timer_chk_click)
        self.statusBar().addWidget(self.timer_chk)
        self.btn_remove=QtWidgets.QPushButton(self)
        self.btn_remove.setText("remove")
        self.btn_remove.clicked.connect(removeOld)
        self.statusBar().addWidget(self.btn_remove)
    def timer_chk_click(self):
        self.timer_run =not self.timer_run
        if self.timer_run:
            self.start_timer()
            self.run()
        else:
            self.stop_timer()
    def start_timer(self):
        if self.timer==None:
            self.timer = QTimer(self)
            self.timer.timeout.connect(self.run)
            self.timer.start(10*60*1000)
        else:
            self.timer.start(10*60*1000)
    def stop_timer(self):
        if self.timer==None:
            pass
        else:
            self.timer.stop()

    def drop_click(self):
        self.drop_hidden=not self.drop_hidden
        if self.drop_hidden:
            self.ui.widget.setVisible(False)
        else:
            self.ui.widget.setVisible(True)
    def file_hidden(self):
        self.show_hidden= not self.show_hidden
        if self.show_hidden:
            self.model.setFilter(QDir.Hidden | QDir.AllEntries)
        else:
            self.model.setFilter(QDir.AllEntries)
    def reset_fav(self):
        self._fav.clear()
        for one in config_json.setting["favorite"]:
            self._fav.addItem(QtWidgets.QListWidgetItem(one))

    def fav_click(self,i):
        item = self._fav.selectedItems()[0]
        self.favorite_one(item.text())
    def new_folder(self):
        name=self.ui.lineEdit_new_folder.text()
        if name=="":
            return
        selections = self.ui.treeView.selectionModel()
        list1 = selections.selectedIndexes()
        if len(list1)==0:
            index=self.model.index(self.l.text())
        else:
            index=list1[0]
        self.model.mkdir(index,name)
    def show_favorite(self):
        from DlgArr import DlgArr
        logging.info(config_json.setting)
        ff = config_json.setting["favorite"]
        d = DlgArr(ff,self.favorite_one)
        r = d.exec_()
        if r == 1:
            config_json.setting["favorite"]=d.model.todos
        else:
            pass        
    def favorite(self):
        selections = self.ui.treeView.selectionModel()
        list1 = selections.selectedIndexes()
        files=[]
        for index in list1:
            if index.column() == 0:
                files.append(self.model.filePath(index))
        if len(files)==0:
            config_json.setting["favorite"].append(self.l.text())
            pass
        else:
            for f  in files:
                if f in config_json.setting["favorite"]:
                    pass
                else:
                    config_json.setting["favorite"].append(f)
        self.reset_fav()
    def paste(self):
        clipboard = QtWidgets.QApplication.clipboard()
        logging.info(dir(clipboard))
        data=clipboard.mimeData()
        logging.info(dir(data))
        urls=data.urls()
        for url in urls:
            logging.info(url)
            if sys.platform == "linux":
                args = ["cp", "-fr", url.toLocalFile(), self.l.text()]
            else:
                args = ["xcopy.exe", "/Y", url.toLocalFile(), self.l.text()]
            self.exec_cmds(args)
        pass
    def copy(self):
        selections = self.ui.treeView.selectionModel()
        list1 = selections.selectedIndexes()
        files=[]
        for index in list1:
            if index.column() == 0:
                files.append(QtCore.QUrl.fromLocalFile(self.model.filePath(index)))
        clipboard = QtWidgets.QApplication.clipboard()
        mime_data = QtCore.QMimeData()
        mime_data.setUrls(files)
        logging.info(mime_data.urls())
        clipboard.setMimeData(mime_data)
        pass
    def delete(self):
        selections = self.ui.treeView.selectionModel()
        list1 = selections.selectedIndexes()
        for index in list1:
            if index.column() == 0:
                self.model.remove(index)
        #    
    def version(self):
        # from version import version
        QMessageBox.about(self, '版本号',str(config_json.setting["version"]))#,QMessageBox.Ok ,QMessageBox.Ok)        
    def goto(self,path):
        path=os.path.abspath(path)
        self.model.setRootPath(path)
        self.l.setText(path)
        index = self.model.index(path)
        self.ui_treeView.sortByColumn(0, Qt.AscendingOrder)
        self.ui_treeView.setRootIndex(index)
        self.ui_treeView.collapseAll()
        self.ui_treeView.expand(index)      #当前项展开
        self.ui_treeView.scrollTo(index)    #定位到当前项
        self.ui_treeView.setColumnWidth(0,260)
    def openMenu(self, position):
        logging.info("openMenu")
        indexes = self.ui_treeView.selectedIndexes()
        logging.info(indexes)
        if len(indexes) > 0:
            index=indexes[0]
            logging.info(self.model.filePath(index))
            menu = QMenu(self)
            officeAction = menu.addAction("office")
            terminalAction = menu.addAction("terminal")
            exeAction = menu.addAction("exec")
            xdgAction = menu.addAction("xdg")
            sublAction = menu.addAction("subl")
            action = menu.exec_(self.mapToGlobal(position))
            if action == officeAction:
                self.openWithOffice(self.model.filePath(index))
            elif action == terminalAction:
                self.openWithTerminal(self.model.filePath(index))
            elif action == exeAction:
                self.execute(self.model.filePath(index))    
            elif action == xdgAction:
                self.xdg(self.model.filePath(index))
            elif action == sublAction:
                self.subl(self.model.filePath(index))                
            # elif action == usedAction:
            #     self.usedChannel()
            # elif action == allAction:
            #     self.allChannel()
            # elif action == validAction:
            #     self.validChannel()
    def edit_finish(self):
        path=self.l.text()
        logging.info(path)
        if os.path.isdir(path):
            self.goto(path)
        elif os.path.isfile(path):
            info=QtCore.QFileInfo(path)
            if info.isExecutable():
                self.exec_cmds([path,])
            else:
                self.exec_cmds["xdg-open",path]
        else:
            (path,filter)=os.path.split(path)
            logging.info(path,filter)
            if os.path.isdir(path):
                self.goto(path)
                self.model.setNameFilters([filter,]);
    def shutdown(self):
        self.exec_cmds(["systemctl","poweroff"])
    def subl(self,path):
        self.exec_cmds(["subl",path])
    def xdg(self,path):
        logging.info("execute====")
        logging.info(path)
        if os.path.isdir(path):
            pass
        else:
            logging.info("xdg")
            self.exec_cmds(["xdg-open",path])
    def execute(self,path):
        logging.info("execute====")
        logging.info("path")
        if os.path.isdir(path):
            pass
        else:
            self.exec_cmds([path])
    def openWithTerminal(self,path):
        logging.info(path)
        if os.path.isdir(path):
            p=path
        else:
            p=os.path.split(path)[0]
        para="--default-working-directory=%s" % p
        self.exec_cmds(["/usr/bin/xfce4-terminal",para])
    def openWithOffice(self,path):
        pass

    def button_cs_pressed(self):
        self.goto(cs0)
    def button_on_pressed(self):
        self.goto(on0)
    def tv_double(self,index):
        file_path=self.model.filePath(index)
        self.startfile(file_path)
    def startfile(self, cmdline):
        cmds=cmdline.split(" ")
        file_path=cmds[0]
        if os.path.isfile(file_path):
            index=self.model.index(file_path)
            file_info=self.model.fileInfo(index)
            if file_info.isExecutable():
                pass
            if sys.platform == "linux":
                excel="xdg-open"
                logging.info(excel,file_path)
                cmds=[excel,file_path]
            else:
                file_path=file_path.replace("/","\\")
                cmds=["cmd.exe","/K","start",file_path]
            self.exec_cmds(cmds)
        elif os.path.isdir(file_path):
            self.goto(file_path)
        else:
            self.exec_cmds(cmds)
    def exec_cmds(self,cmds):
        try:
            subprocess.Popen(cmds)
        except FileNotFoundError:
            logging.info("file not found:"+str(cmds))

    def button2_pressed(self):
        self.goto("/")
    def clip(self):
        logging.info("clip")
        clipboard = QApplication.clipboard()
        t=clipboard.text()
        logging.info(t)
        if t!="":
            path='HKEY_CURRENT_USER\\Environment'
            setting2 = QSettings(path, QSettings.NativeFormat)
            lines=t.split("\n")
            for l in lines:
                fs=l.split("=")
                if len(fs)==2:
                    logging.info(fs)
                    setting2.setValue(fs[0],fs[1])

    def show_dlgapp(self):
        from DlgApps import DlgApps
        logging.info(config_json.setting)
        ff = config_json.setting["apps"]
        d = DlgApps(ff)
        r = d.exec_()
        if r == 1:
            config_json.setting["apps"]=d.model.todos
            # self.refresh_ff2()
        else:
            pass
    def favorite_one(self,p):
        self.startfile(p)
    def run(self):
        # try:#OSError
        logging.info("timer run")
        try:
            txt="%d/%d %d/%d" % (len(os.listdir(cs0)),len(os.listdir(cs1)),len(os.listdir(on0)),len(os.listdir(on1)))
            if txt!=self.txt:
                self.txt=txt
                self.label.setText(txt)
                self.updated.emit(txt)
        except FileNotFoundError:
            pass
        # except OSError:#network not connected
        #     logging.info("OSError==")
        #     pass
    def leftBottom(self):
        self.resize(300,300)
        screen = QDesktopWidget().screenGeometry()
        # 获取窗口坐标系
        size = self.geometry()
        logging.info(size)
        newLeft = 0
        newTop =screen.height() -80-size.height()
        self.move(int(newLeft),int(newTop))
def qingyun_style(a):
    from PyQt5.QtGui import QPalette,QColor
    # f=open("qss/lightblue.css", "r") 
    f=open("qss/blacksoft.css", "r") 
    # f=open("qss/flatgray.css", "r") 
    _style = f.read()
    # logging.info(_style)
    paletteColor=_style[20:20+7]
    # logging.info(paletteColor)
    a.setPalette(QPalette(QColor(paletteColor)));
    a.setStyleSheet(_style);
def github_style(a):
    # with open("qss/ManjaroMix.qss", "r") as f:
    # with open("qss/Ubuntu.qss", "r") as f:
    # with open("qss/NeonButtons.qss", "r") as f:
    f=open("qss/MaterialDark.qss", "r")
    # with open("qss/AMOLED.qss", "r") as f:
    # with open("qss/ConsoleStyle.qss", "r") as f:
    # f=open("qss/MacOS.qss", "r")
    # f=open("qss/ElegantDark.qss", "r")
    a.setStyleSheet(f.read());     
def dark_style(a) :   
    import qdarkstyle
    dark_stylesheet = qdarkstyle.load_stylesheet_pyqt5()
    a.setStyleSheet(dark_stylesheet)
def material_style(a):
    from qt_material import apply_stylesheet
    apply_stylesheet(a, theme='dark_cyan.xml') 
if __name__ == "__main__":
    import sys
    import getpath
    import os
    import logging
    from logging.handlers import RotatingFileHandler
    sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
    sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1)
    handlers=[RotatingFileHandler(filename="explore.log", maxBytes=10*1024*1024,backupCount=3),# logging.FileHandler(initpath+'/myapp.log'),
            logging.StreamHandler(sys.stdout)
    ]
    # handlers=[logging.StreamHandler(sys.stdout)]
    logging.basicConfig(level=logging.DEBUG,
                        format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                        handlers=handlers)
    logging.info('begin')

    a = QApplication(sys.argv)
    # qingyun_style(a)
    # dark_style(a)
    a.lastWindowClosed.connect(a.quit)
    w = MainW()
    # w.leftBottom()
    # w.showMaximized()
    ti = TrayIcon(w)
    ti.show()
    # ti.showMsg("test show Message")
    a.exec_()
